package com.zzty.zzlp.socket;

import com.zzty.zzlp.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @desp Socket处理类
 */
@Service
public class SocketHandler implements WebSocketHandler {

    private static final Logger logger;
    private static final ArrayList<WebSocketSession> users;

    static {
        users = new ArrayList<WebSocketSession>();
        logger = LoggerFactory.getLogger(SocketHandler.class);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        logger.info("成功建立socket连接");
        users.add(session);
        if (session.getAttributes().get("userId") != null) {

            SessionUtils.put(session.getAttributes().get("userId").toString(), session);
            System.out.println("当前有：" + SessionUtils.clients.size() + "用户在线");
            String username = session.getAttributes().get("userId").toString();
            if (username != null) {
                //session.sendMessage(new TextMessage("我们已经成功建立socket通信了"));
            }

        }

    }

    @Override
    public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.print("11111111111");
        arg0.sendMessage(arg1);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable error)
            throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.error("连接出现错误:" + error.toString());
        SessionUtils.remove(session.getAttributes().get("userId").toString());

        //users.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1)
            throws Exception {
        logger.debug("连接已关闭");
        SessionUtils.remove(session.getAttributes().get("userId").toString());
        //	users.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        try {
            if (SessionUtils.get(userName).isOpen()) {
                System.out.println(message);
                SessionUtils.get(userName).sendMessage(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
